/*
 *      Copyright (c) 2018-2028, Chill Zhuang All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions are met:
 *
 *  Redistributions of source code must retain the above copyright notice,
 *  this list of conditions and the following disclaimer.
 *  Redistributions in binary form must reproduce the above copyright
 *  notice, this list of conditions and the following disclaimer in the
 *  documentation and/or other materials provided with the distribution.
 *  Neither the name of the dreamlu.net developer nor the names of its
 *  contributors may be used to endorse or promote products derived from
 *  this software without specific prior written permission.
 *  Author: Chill 庄骞 (smallchill@163.com)
 */
package org.springblade.metadata.app;


import java.util.List;
import java.util.Map;

import javax.validation.Valid;

import org.apache.atlas.AtlasServiceException;
import org.apache.commons.lang3.StringUtils;
import org.springblade.core.boot.ctrl.BladeController;
import org.springblade.core.cache.utils.CacheUtil;
import org.springblade.core.mp.support.Condition;
import org.springblade.core.secure.BladeUser;
import org.springblade.core.tenant.annotation.NonDS;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.api.ResultCode;
import org.springblade.core.tool.support.Kv;
import org.springblade.core.tool.utils.Func;
import org.springblade.metadata.entity.Category;
import org.springblade.metadata.service.ICategoryService;
import org.springblade.metadata.service.impl.GossaryService;
import org.springblade.metadata.vo.CheckedTreeVO;
import org.springblade.metadata.vo.GrantTreeVO;
import org.springblade.metadata.vo.CategoryVO;
import org.springblade.metadata.vo.CategoryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.AllArgsConstructor;
import springfox.documentation.annotations.ApiIgnore;


/**
 * 控制器
 *
 * @author Chill
 */
@NonDS
@RestController
@AllArgsConstructor
@RequestMapping("v2/category")
@Api(value = "group", tags = "group")
public class CategoryController extends BladeController {

	private final ICategoryService categoryService;
    final String  MENU_CACHE="metadata:cache";
	/**
	 * 详情
	 */
	@GetMapping("/detail")
	@ApiOperationSupport(order = 1)
	@ApiOperation(value = "详情", notes = "传入menu")
	public R<CategoryVO> detail(Category menu) {
		Category detail = categoryService.getOne(Condition.getQueryWrapper(menu));
		return R.data(CategoryWrapper.build().entityVO(detail));
	}

	/**
	 * 列表
	 */
	@GetMapping("/list")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "code", value = "目录编号", paramType = "query", dataType = "string"),
		@ApiImplicitParam(name = "name", value = "目录名称", paramType = "query", dataType = "string")
	})
	@ApiOperationSupport(order = 2)
	@ApiOperation(value = "列表", notes = "传入menu")
	public R<List<CategoryVO>> list(@ApiIgnore @RequestParam Map<String, Object> menu) {
		List<Category> list = categoryService.list(Condition.getQueryWrapper(menu, Category.class).lambda().orderByAsc(Category::getSort));
		return R.data(CategoryWrapper.build().listNodeVO(list));
	}

	/**
	 * 懒加载列表
	 */
	@GetMapping("/lazy-list")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "code", value = "目录编号", paramType = "query", dataType = "string"),
		@ApiImplicitParam(name = "name", value = "目录名称", paramType = "query", dataType = "string")
	})
	@ApiOperationSupport(order = 3)
	@ApiOperation(value = "懒加载列表", notes = "传入menu")
	public R<List<CategoryVO>> lazyList(Long parentId, @ApiIgnore @RequestParam Map<String, Object> menu) {
		List<CategoryVO> list = categoryService.lazyList(parentId, menu);
		return R.data(CategoryWrapper.build().listNodeLazyVO(list));
	}

	/**
	 * 目录列表
	 */
	@GetMapping("/menu-list")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "code", value = "目录编号", paramType = "query", dataType = "string"),
		@ApiImplicitParam(name = "name", value = "目录名称", paramType = "query", dataType = "string")
	})
	@ApiOperationSupport(order = 4)
	@ApiOperation(value = "目录列表", notes = "传入menu")
	public R<List<CategoryVO>> menuList(@ApiIgnore @RequestParam Map<String, Object> menu) {
		List<Category> list = categoryService.list(Condition.getQueryWrapper(menu, Category.class).lambda().eq(Category::getCategory, 1).orderByAsc(Category::getSort));
		return R.data(CategoryWrapper.build().listNodeVO(list));
	}

	/**
	 * 懒加载目录列表
	 */
	@GetMapping("/lazy-menu-list")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "code", value = "目录编号", paramType = "query", dataType = "string"),
		@ApiImplicitParam(name = "name", value = "目录名称", paramType = "query", dataType = "string")
	})
	@ApiOperationSupport(order = 5)
	@ApiOperation(value = "懒加载目录列表", notes = "传入menu")
	public R<List<CategoryVO>> lazyCategoryList(Long parentId, @ApiIgnore @RequestParam Map<String, Object> menu) {
		List<CategoryVO> list = categoryService.lazyCategoryList(parentId, menu);
		return R.data(CategoryWrapper.build().listNodeLazyVO(list));
	}

	/**
	 * 新增或修改
	 */
	@PostMapping("/submit")
	@ApiOperationSupport(order = 6)
	@ApiOperation(value = "新增或修改", notes = "传入Category")
	public R submit(@Valid @RequestBody Category c) {
		if(StringUtils.isBlank(c.getCode())) {
			return R.fail(ResultCode.PARAM_MISS,"code");
		}
		Category  cc = categoryService.getBydCode(c.getCode());
		if(cc !=null ) {
			if(c.getId()== null || c.getId().longValue() != cc.getId().longValue()) {
				return R.fail(ResultCode.PARAM_VALID_ERROR,"code exist");
			}
		}
		if (categoryService.submit(c)) {
			CacheUtil.clear(MENU_CACHE);
			CacheUtil.clear(MENU_CACHE, Boolean.FALSE);
			// 返回懒加载树更新节点所需字段
			Kv kv = Kv.create().set("id", String.valueOf(c.getId()));
			return R.data(kv);
		}
		return R.fail("操作失败");
	}

	/**
	 * 新增或修改
	 */
	@PostMapping("/create")
	@ApiOperationSupport(order = 31)
	@ApiOperation(value = "新增或修改", notes = "传入Category,No verification code")
	public R create(@Valid @RequestBody Category c) {
		if (categoryService.submit(c)) {
			CacheUtil.clear(MENU_CACHE);
			CacheUtil.clear(MENU_CACHE, Boolean.FALSE);
			// 返回懒加载树更新节点所需字段
			Kv kv = Kv.create().set("id", String.valueOf(c.getId()));
			return R.data(kv);
		}
		return R.fail("操作失败");
	}
	
	@Autowired()
	private  GossaryService  gossaryService;
	/**
	 * assignentity
	 */
	@PostMapping("/assignentity")
	@ApiOperationSupport(order = 32)
	@ApiOperation(value = "assignentity", notes = "传入ids")
	public R assignEntity(@ApiParam(value = "entity guid ", required = true) @RequestParam String ids,@ApiParam(value = "category id", required = true) @RequestParam Long id) {
		Category c = categoryService.getById(id);
		
		if(c == null) {
			return R.fail(ResultCode.FAILURE);
		}
		
		try {
			String termid = gossaryService.getGuidByCategaryid(c);
			gossaryService.assignTermToEntities(termid, ids);
		} catch (AtlasServiceException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return R.success(ResultCode.SUCCESS);
	}
	
	/**
	 * assignentity
	 */
	@PostMapping("/disassignentity")
	@ApiOperationSupport(order = 33)
	@ApiOperation(value = "assignentity", notes = "传入ids")
	public R disAssignentity(@ApiParam(value = "entity guid ", required = true) @RequestParam String ids,@ApiParam(value = "category id", required = true) @RequestParam Long id) {
		Category c = categoryService.getById(id);
		
		if(c == null) {
			return R.fail(ResultCode.FAILURE);
		}
		
		try {
			String termid = gossaryService.getGuidByCategaryid(c);
			gossaryService.disAssignTermToEntities(termid, ids);
		} catch (AtlasServiceException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return R.success(ResultCode.SUCCESS);
	}
	/**
	 * 删除
	 */
	@PostMapping("/removemetadata")
	@ApiOperationSupport(order = 34)
	@ApiOperation(value = "删除", notes = "传入ids")
	public R removemetadata(@ApiParam(value = "主键集合", required = true) @RequestParam String ids) {
		
		
		CacheUtil.clear(MENU_CACHE);
		CacheUtil.clear(MENU_CACHE, Boolean.FALSE);
		try {
			return R.status(gossaryService.remove(ids));
		} catch (AtlasServiceException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return R.fail(ResultCode.FAILURE, e.getMessage());
		}
	}
	/**
	 * 删除
	 */
	@PostMapping("/remove")
	@ApiOperationSupport(order = 7)
	@ApiOperation(value = "删除", notes = "传入ids")
	public R remove(@ApiParam(value = "主键集合", required = true) @RequestParam String ids) {
		CacheUtil.clear(MENU_CACHE);
		CacheUtil.clear(MENU_CACHE, Boolean.FALSE);
		return R.status(categoryService.removeCategory(ids));
	}

	/**
	 * 前端目录数据
	 */
	@GetMapping("/routes")
	@ApiOperationSupport(order = 8)
	@ApiOperation(value = "前端目录数据", notes = "前端目录数据")
	public R<List<CategoryVO>> routes(BladeUser user, Long topCategoryId,String category) {
		if(StringUtils.isBlank(category)) {
			category = "0";
		}
		List<CategoryVO> list = categoryService.routes((user == null) ? null : user.getRoleId(), topCategoryId,category);
		return R.data(list);
	}

	/**
	 * 前端按钮数据
	 */
	@GetMapping("/buttons")
	@ApiOperationSupport(order = 10)
	@ApiOperation(value = "前端按钮数据", notes = "前端按钮数据")
	public R<List<CategoryVO>> buttons(BladeUser user) {
		List<CategoryVO> list = categoryService.buttons(user.getRoleId());
		return R.data(list);
	}

	/**
	 * 获取目录树形结构
	 */
	@GetMapping("/tree")
	@ApiOperationSupport(order = 11)
	@ApiOperation(value = "树形结构", notes = "树形结构")
	public R<List<CategoryVO>> tree() {
		List<CategoryVO> tree = categoryService.tree();
		return R.data(tree);
	}

	/**
	 * 获取权限分配树形结构
	 */
	@GetMapping("/grant-tree")
	@ApiOperationSupport(order = 12)
	@ApiOperation(value = "权限分配树形结构", notes = "权限分配树形结构")
	public R<GrantTreeVO> grantTree(BladeUser user) {
		GrantTreeVO vo = new GrantTreeVO();
		vo.setCategory(categoryService.grantTree(user));
		vo.setDataScope(categoryService.grantDataScopeTree(user));
		vo.setApiScope(categoryService.grantApiScopeTree(user));
		return R.data(vo);
	}

	/**
	 * 获取权限分配树形结构
	 */
	@GetMapping("/role-tree-keys")
	@ApiOperationSupport(order = 13)
	@ApiOperation(value = "角色所分配的树", notes = "角色所分配的树")
	public R<CheckedTreeVO> roleTreeKeys(String roleIds) {
		CheckedTreeVO vo = new CheckedTreeVO();
		vo.setCategory(categoryService.roleTreeKeys(roleIds));
		vo.setDataScope(categoryService.dataScopeTreeKeys(roleIds));
		vo.setApiScope(categoryService.apiScopeTreeKeys(roleIds));
		return R.data(vo);
	}

	/**
	 * 获取顶部目录树形结构
	 */
	@GetMapping("/grant-top-tree")
	@ApiOperationSupport(order = 14)
	@ApiOperation(value = "顶部目录树形结构", notes = "顶部目录树形结构")
	public R<GrantTreeVO> grantTopTree(BladeUser user) {
		GrantTreeVO vo = new GrantTreeVO();
		vo.setCategory(categoryService.grantTopTree(user));
		return R.data(vo);
	}

	/**
	 * 获取顶部目录树形结构
	 */
	@GetMapping("/top-tree-keys")
	@ApiOperationSupport(order = 15)
	@ApiOperation(value = "顶部目录所分配的树", notes = "顶部目录所分配的树")
	public R<CheckedTreeVO> topTreeKeys(String topCategoryIds) {
		CheckedTreeVO vo = new CheckedTreeVO();
		vo.setCategory(categoryService.topTreeKeys(topCategoryIds));
		return R.data(vo);
	}


	/**
	 * 获取配置的角色权限
	 */
	@GetMapping("auth-routes")
	@ApiOperationSupport(order = 17)
	@ApiOperation(value = "目录的角色权限")
	public R<List<Kv>> authRoutes(BladeUser user) {
		if (Func.isEmpty(user)) {
			return null;
		}
		return R.data(categoryService.authRoutes(user));
	}
}
